package com.lost.octopus.es.helper.entity.query.highlight;

import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.util.HashMap;
import java.util.Map;

/**
 * 默认简单高亮返回处理 要扩展请注册 {@link HighlightDeal} Bean
 * @author zhangbh
 **/
public class SimpleFileHighlightDeal implements HighlightDeal {

    /**
     * 默认字段转换高亮名称=fieldName加 Highlight
     * @param fieldName 字段名
     * @return 高亮名称
     */
    protected String getTransField(String fieldName) {
        return fieldName + "Highlight";
    }

    @Override
    public void doTransHighlightFields(Map<String, Object> source, Map<String, HighlightField> fields) {
        // 最终的map
        Map<String, StringBuilder> matchFieldMap = new HashMap<>(fields.size());
        fields.forEach((fieldName, highlightField) -> {
            // 匹配到的数据
            Text[] fragments = highlightField.getFragments();
            // 转换后放的字段名
            String transField = getTransField(fieldName);
            StringBuilder builder = matchFieldMap.get(transField);
            if (builder == null) {
                builder = new StringBuilder();
                matchFieldMap.put(transField, builder);
            }
            // 循环加入高亮信息
            for (Text fragment : fragments) {
                builder.append(fragment);
            }
        });
        // 放入字段
        matchFieldMap.forEach((transField, value) -> source.put(transField, value.toString()));
    }
}
